package grpc

import (
	"base_server/internal/models/works"
	"base_server/internal/models/works_collection"
	"context"
	"golang.org/x/sync/errgroup"
	"jihe.common/protos/base_server/proto"
)

func (s *Server) BaseCreateWorksCollection(c context.Context, in *proto.BaseWorksCollectionWorks) (out *proto.BaseNull, err error) {
	out = new(proto.BaseNull)
	sql := s.Pgsql.Get()
	tx, err := sql.Begin()
	if err != nil {
		return
	}
	worksCollectionTbl := works_collection.NewTx(tx)
	collection, err := worksCollectionTbl.Create(in.Collection)
	if err != nil {
		_ = tx.Rollback()
		return
	}
	in.Collection.Id = collection.Id
	worksTbl := works.NewTx(tx)
	err = worksTbl.Create(in)
	if err != nil {
		_ = tx.Rollback()
		return
	}
	err = tx.Commit()
	return
}

func (s *Server) BaseUpdateWorksCollection(c context.Context, in *proto.BaseWorksCollectionWorks) (out *proto.BaseNull, err error) {
	out = new(proto.BaseNull)
	sql := s.Pgsql.Get()
	tx, err := sql.Begin()
	if err != nil {
		return
	}
	worksCollectionTbl := works_collection.NewTx(tx)
	err = worksCollectionTbl.Update(in.Collection)
	if err != nil {
		_ = tx.Rollback()
		return
	}
	worksTbl := works.NewTx(tx)
	err = worksTbl.Delete(in.Collection.Id)
	if err != nil {
		_ = tx.Rollback()
		return
	}
	err = worksTbl.Create(in)
	if err != nil {
		_ = tx.Rollback()
		return
	}
	err = tx.Commit()
	return
}

func (s *Server) BaseGetWorksCollectionList(c context.Context, in *proto.BaseWorksCollection) (out *proto.BaseWorksCollections, err error) {
	out = new(proto.BaseWorksCollections)
	db := s.Pgsql.Get()
	worksCollectionTbl := works_collection.NewModel(db)
	out.List, err = worksCollectionTbl.GetListByUid(in.Uid)
	return
}

func (s *Server) BaseGetWorksCollectionDetail(c context.Context, in *proto.BaseWorksCollection) (out *proto.BaseWorksCollectionWorks, err error) {
	out = new(proto.BaseWorksCollectionWorks)
	db := s.Pgsql.Get()
	worksCollectionTbl := works_collection.NewModel(db)
	worksTbl := works.NewModel(db)
	var g errgroup.Group
	g.Go(func() error {
		out.Collection, err = worksCollectionTbl.DetailById(in.Id)
		if err != nil {
			return err
		}
		return nil
	})
	g.Go(func() error {
		out.List, err = worksTbl.GetByWorksCollectionId(in.Id)
		if err != nil {
			return err
		}
		return nil
	})
	err = g.Wait()
	if err != nil {
		return
	}
	return
}

func (s *Server) BaseDeleteWorksCollection(c context.Context, in *proto.BaseWorksCollection) (out *proto.BaseNull, err error) {
	out = new(proto.BaseNull)
	db := s.Pgsql.Get()
	tx, err := db.Begin()
	if err != nil {
		return
	}
	worksCollectionTbl := works_collection.NewTx(tx)
	worksTbl := works.NewTx(tx)
	err = worksCollectionTbl.Delete(in.Id)
	if err != nil {
		_ = tx.Rollback()
		return
	}
	err = worksTbl.Delete(in.Id)
	if err != nil {
		_ = tx.Rollback()
		return
	}
	err = tx.Commit()
	return
}
